<!--
 * @Author: hucc
 * @Date: 2021-10-18 11:15:11
 * @LastEditors: hucc
 * @LastEditTime: 2021-10-18 18:44:32
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../../js/vue.js"></script>
    <script src="../../js/vue-router.js"></script>
    <script src="../../js/vuex.js"></script>
    <script src="../../js/axios.js"></script>
    <script src="../../js/qs.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <style>
        .head {
            height: 50px;
            font-size: 32px;
            text-align: center;
            background-color: #409eff;
            color: white
        }
        
        .main {
            height: 800px;
            display: flex;
            margin-top: 20px;
        }
        
        .left {
            width: 200px;
            border: 3px solid olive;
            margin-right: 30px;
        }
        
        .left:hover {
            cursor: pointer;
        }
        
        .button {
            width: 200px;
            margin-bottom: 10px;
        }
        
        .right {
            flex-direction: row;
            flex: 1;
            border: 3px solid blueviolet;
        }
    </style>
</head>

<body>
    <div id="app">
        <router-view></router-view>

    </div>
    <script>
        //全局配置axios默认值
        axios.defaults.baseURL = "http://39.103.202.53:8888";
        let {

            mapState,
            mapActions
        } = Vuex;
        //1.声明组件
        let comLogin = {
            data() {
                return {
                    loginData: {}
                }
            },
            methods: {
                //把状态机子模块的方法映射到组件的methods里
                ...mapActions('login', ['login']),
                toLogin() {
                    //判断当前登录输入框值是否全部输入
                    if (this.loginData.username && this.loginData.password) {
                        //调用当前状态机中的actions方法 用的是axios发送请求 返回值是promise实例
                        this.login(this.loginData).then(res => {
                            sessionStorage.setItem('token', res.data.data.token);
                            //登陆成功后跳转至首页
                            this.$router.push('/index');
                        })
                    } else {
                        alert('用户名，密码不能为空')
                    }
                }
            },
            template: `
              <div>
                <h3>欢迎请登录！</h3>
                <el-form :model='loginData' label-with='80px'>
            <el-form-item label='用户名'>
                <el-input v-model='loginData.username'></el-input>
            </el-form-item>
            <el-form-item label='密码'>
                <el-input v-model='loginData.password'></el-input>
            </el-form-item>
            <el-form-item >
                <el-button type='primary' @click='toLogin'>登录</el-button>
            </el-form-item>
            </el-form>
                </div>
            `
        }
        let comIndex = {
                data() {
                    return {};
                },
                template: `
              <div>
                 <h3 class='head'>欢迎使用</h3>
                 <div class='main'>
                 <div class='left'>
                 <div><el-button type='primary' @click="$router.push('/index/category')" class='button'>栏目管理</el-button></div>
                 <div><el-button type='primary'  @click="$router.push('/index/article')"  class='button'>文章管理</el-button></div>
                 </div>
                 <div class='right'>
                    <router-view></router-view>
                    </div>
                    </div>
                </div>
            `
            }
            //定义组件 comCategory
        let comCategory = {
                data() {
                    return {}
                },
                computed: {
                    ...mapState('category', ['categories'])
                },
                methods: {
                    ...mapActions('category', ['findAllCategories'])
                },
                created() {
                    this.findAllCategories();
                },
                template: `
                   <div>
                    <el-table :data='categories' style='width:100%'>
                    <el-table-column prop='name' label='栏目名称'></el-table-column>
                    <el-table-column prop="id" label='编号'></el-table-column>
                    <el-table-column prop='parentId' label='所属栏目'></el-table-column>
                    <el-table-column prop='description' label='栏目描述'></el-table-column>
                    </el-table>
                    </div>
                `
            }
            //定义组件comArticle
        let comArticle = {
                data() {
                    return {}
                },
                computed: {
                    ...mapState('article', ['articles'])
                },
                methods: {
                    ...mapActions('article', ['findAllArticles'])
                },
                created() {
                    this.findAllArticles();
                },
                template: `
                   <div>
                    <el-table :data='articles' style='width:100%'>
                        <el-table-column prop='id' label='编号'></el-table-column>
                    <el-table-column prop='title' label='文章标题'></el-table-column>
                    <el-table-column prop='readTimes' label='阅读次数'></el-table-column>
                    <el-table-column prop='categoryId' label='栏目编号'></el-table-column>
                    </el-table>
                    </div>
                  `
            }
            //2.定义路由实例
        let router = new VueRouter({
                routes: [{
                    path: '/',
                    redirect: '/login'
                }, {
                    path: '/login',
                    component: comLogin
                }, {
                    path: '/index',
                    component: comIndex,
                    children: [{
                        path: '/index/category',
                        component: comCategory
                    }, {
                        path: '/index/article',
                        component: comArticle
                    }]
                }, ]
            })
            //2.1路由全局守卫
        router.beforeEach((to, from, next) => {
                //获取token
                const token = sessionStorage.getItem('token');
                if (to.path != '/login' && !token) {
                    alert('请先登录!')
                        //未登录状态下直接通过修改url地址形式跳转至首页
                        //使用守卫拦截 并且强行返回登陆页面
                    next('/login')
                } else {
                    next();
                }
            })
            //声明状态机子模块 
        let moduleLogin = {
            namespaced: true,
            state() {
                return {
                    token: null
                }
            },
            actions: {
                async login(context, data) {
                    let res = await axios.post('user/login', data)
                    return res;
                }
            }
        }
        let moduleCategory = {
                namespaced: true,
                state() {
                    return {
                        categories: [],
                    }
                },
                mutations: {
                    SET_CATEGORIES(state, payload) {
                        state.categories = payload;
                    }
                },
                actions: {
                    async findAllCategories({
                        commit
                    }) {
                        //携带token去查询栏目信息
                        const token = sessionStorage.getItem('token');
                        let res = await axios.get('/category/findAll', {
                            headers: {
                                'Authorization': token
                            }
                        });
                        commit('SET_CATEGORIES', res.data.data);
                    }
                }
            }
            //定义状态机moduleArticle子模块
        let moduleArticle = {
                namespaced: true,
                state() {
                    return {
                        articles: []
                    }
                },
                mutations: {
                    SET_ARTICLES(state, payload) {
                        state.articles = payload;
                    }
                },
                actions: {
                    async findAllArticles({
                        commit
                    }) {
                        //携带token去查询栏目信息
                        const token = sessionStorage.getItem('token');
                        let res = await axios.get('/article/findAll', {
                            headers: {
                                'Authorization': token
                            }
                        });
                        commit('SET_ARTICLES', res.data.data);
                    }
                }
            }
            //3.声明状态 机实例
        let store = new Vuex.Store({
            modules: {
                login: moduleLogin,
                category: moduleCategory,
                article: moduleArticle
            }
        })
        new Vue({
            el: '#app',
            data: {},
            methods: {},
            created() {},
            components: {},
            router,
            store
        })
    </script>
</body>

</html>